from django.shortcuts import render
from django.http import HttpResponse
from web.settings import BASE_DIR
from .. import models
import time,os

# Create your views here.
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
# 数据分页
from django.core.paginator import Paginator
from . viewsIndex import uploads


# 添加会员
def useradd(request):
    # 判断当前的请求方式
    if request.method == 'GET':
        # 加载表单页面
        return render(request,'myadmin/users/add.html')

    elif request.method == 'POST':
        try:
            # 接收数据,进行数据
            data = request.POST.dict()

            data.pop('csrfmiddlewaretoken')
            # 密码加密
            # 对密码进行加密操作 
            data['password'] = make_password(data['password'],None,'pbkdf2_sha256')
            # 判断年龄是否为空
            if data['age'] == '':
                data['age'] = None
            # 头像上传
            myfile = request.FILES.get('pic_url')
            if myfile:
                data['pic_url'] = uploads(myfile)
            else:
                data['pic_url'] = '/static/pics/a.jpg'

            db = models.Users(**data)
            db.save()

            return HttpResponse('<script>alert("添加会员成功");location.href="'+reverse('myadmin_user_index')+'"</script>')

        except :
            return HttpResponse('<script>alert("添加会员失败");location.href="'+reverse('myadmin_user_add')+'"</script>')

# 会员显示视图
def userindex(request):
    
    # 获取所有会员信息
    data = models.Users.objects.filter().exclude(status=3)

    # 获取搜索条件
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == 'all':
            # 用于查询or
            from django.db.models import Q
            data = data.filter(Q(username__contains=keywords)|Q(tel__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))

        # 状态搜索
        elif types == 'status':
            arr = {'正常':0,'禁用':1,'注销':3}
            data = data.filter(status=arr[keywords])

        # 单项搜索
        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)   

    # 实例化分页类
    paginator = Paginator(data,10)

    # 获取当前页码数
    p = request.GET.get('p',1)

    # 获取当前页的数据
    userlist = paginator.page(p)

    # 数据分配
    context = {'userlist':userlist}

    return render(request,'myadmin/users/index.html',context)

# 会员的逻辑删除
def userdel(request,uid):
    try:
        # 获取逻辑删除的id
        db = models.Users.objects.get(id = uid)
        # 修改状态值
        db.status = 3
        db.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_user_index')+'"</script>')  

# 会员的信息修改
def useredit(request,uid):

    db = models.Users.objects.get(id=uid)
    # 判断请求方式
    if request.method == 'GET':

        return render(request,'myadmin/users/edit.html',{'uinfo':db})

    elif request.method == 'POST':

        db.username = request.POST.get('username')

        if request.POST.get('password'):

            db.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')

        db.sex = request.POST.get('sex')
        if db.sex == '':
            db.sex = None
        db.age = request.POST.get('age')
        if db.age == '':
            db.age = None
        db.tel = request.POST.get('tel')
        db.email = request.POST.get('email')
        # 判断是否更新了头像
        myfile = request.FILES.get('pic_url')
        if myfile:
            # 如果修改了头像,要上传新的头像,并判断是否删除以前头像
            if db.pic_url != '/static/pics/a.jpg' :
                try:
                    # 删除原来上传的头像
                    os.remove(BASE_DIR+db.pic_url)
                except:
                    pass                
            # 更新头像
            db.pic_url = uploads(myfile)
        db.save()

        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_user_index')+'"</script>')

# 注销会员列表 logout注销
def userlogout(request):
    # 获取注销会员数据
    data = models.Users.objects.filter(status=3)
    
    # 获取搜索条件
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == 'all':
            # 用于查询or
            from django.db.models import Q
            data = data.filter(Q(username__contains=keywords)|Q(tel__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords))

        # 状态搜索
        elif types == 'status':
            arr = {'正常':0,'禁用':1,'注销':3}
            data = data.filter(status=arr[keywords])

        # 单项搜索
        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)   

    # 实例化分页类
    paginator = Paginator(data,10)

    # 获取当前页码数
    p = request.GET.get('p',1)

    # 获取当前页的数据
    userlist = paginator.page(p)

    # 分配数据
    context = {'userlist':userlist}
   
    return render(request,'myadmin/users/logout.html',context)
